import { NextRequest, NextResponse } from 'next/server';
import { mockUsers, generateMockUser } from '@/mock/users';
import { User, CreateUserRequest, UserFilters, PaginatedResponse, ApiResponse } from '@/types/user';

// 模拟数据存储
let users: User[] = [...mockUsers];

// GET /api/users - 获取用户列表
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    
    // 解析查询参数
    const page = parseInt(searchParams.get('page') || '1');
    const pageSize = parseInt(searchParams.get('pageSize') || '10');
    const status = searchParams.get('status')?.split(',');
    const role = searchParams.get('role')?.split(',');
    const department = searchParams.get('department')?.split(',');
    const search = searchParams.get('search');

    // 过滤用户
    let filteredUsers = users;

    if (status?.length) {
      filteredUsers = filteredUsers.filter(user => status.indexOf(user.status) >= 0);
    }

    if (role?.length) {
      filteredUsers = filteredUsers.filter(user => role.indexOf(user.role) >= 0);
    }

    if (department?.length) {
      filteredUsers = filteredUsers.filter(user => 
        user.department && department.indexOf(user.department) >= 0
      );
    }

    if (search) {
      const searchLower = search.toLowerCase();
      filteredUsers = filteredUsers.filter(user =>
        user.username.toLowerCase().includes(searchLower) ||
        user.displayName.toLowerCase().includes(searchLower) ||
        user.email.toLowerCase().includes(searchLower) ||
        (user.department && user.department.toLowerCase().includes(searchLower)) ||
        (user.position && user.position.toLowerCase().includes(searchLower))
      );
    }

    // 排序（按创建时间倒序）
    filteredUsers.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

    // 分页
    const total = filteredUsers.length;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedUsers = filteredUsers.slice(startIndex, endIndex);

    const response: ApiResponse<PaginatedResponse<User>> = {
      success: true,
      data: {
        data: paginatedUsers,
        total,
        page,
        pageSize,
      },
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('获取用户列表失败:', error);
    return NextResponse.json(
      { success: false, message: '获取用户列表失败' },
      { status: 500 }
    );
  }
}

// POST /api/users - 创建新用户
export async function POST(request: NextRequest) {
  try {
    const body: CreateUserRequest = await request.json();

    // 验证必填字段
    if (!body.username || !body.email || !body.displayName || !body.password) {
      return NextResponse.json(
        { success: false, message: '用户名、邮箱、显示名称和密码为必填字段' },
        { status: 400 }
      );
    }

    // 检查用户名和邮箱是否已存在
    const existingUser = users.find(u => u.username === body.username || u.email === body.email);
    if (existingUser) {
      return NextResponse.json(
        { success: false, message: '用户名或邮箱已存在' },
        { status: 400 }
      );
    }

    // 创建新用户
    const newUser = generateMockUser({
      username: body.username,
      email: body.email,
      displayName: body.displayName,
      role: body.role,
      department: body.department,
      position: body.position,
      phone: body.phone,
    });

    // 添加到数据存储
    users.unshift(newUser);

    const response: ApiResponse<User> = {
      success: true,
      data: newUser,
      message: '用户创建成功',
    };

    return NextResponse.json(response, { status: 201 });
  } catch (error) {
    console.error('创建用户失败:', error);
    return NextResponse.json(
      { success: false, message: '创建用户失败' },
      { status: 500 }
    );
  }
} 